/* 
描述：定义问题管理模块的相关后端接口 
完成人：吴悠 
完成时间: 2025/04/27
*/
package com.jiesenhe.qacommunity.controller;

import com.jiesenhe.qacommunity.pojo.Comment;
import com.jiesenhe.qacommunity.pojo.Question;
import com.jiesenhe.qacommunity.pojo.QuestionTag;
import com.jiesenhe.qacommunity.pojo.Tag;
import com.jiesenhe.qacommunity.service.QuestionService;
import com.jiesenhe.qacommunity.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/question")
public class QuestionController {
    @Autowired
    QuestionService questionService;

    @PostMapping("/getQuestionList")
    public ResponseEntity<Object> getQuestionList(@RequestBody Question question)
    {
        List<Question> list = questionService.getQuestionList(question);
        return ResponseEntity.ok(new java.util.HashMap<String, Object>() {
            {
                put("code", (list != null && !list.isEmpty()) ? 1 : 0);
                put("msg", (list != null && !list.isEmpty()) ? "success" : "failed");
                put("data", list);
            }
        });
    }

    @PostMapping("/insertQuestion")
    public ResponseEntity<Object> insertQuestion(@RequestBody Question question, HttpServletRequest request)
    {
        String token = request.getHeader("Token");
        if (JwtUtil.checkToken(token)){
            int result = questionService.insertQuestion(question);
            int lastQuestionId =  questionService.getLastQuestionId();
            return ResponseEntity.ok(new java.util.HashMap<String, Object>() {
                {
                    put("code", result != 0 ? 1 : 0);
                    put("msg", result != 0 ? "insertQuestion success" : "insertQuestion failed");
                    put("data", lastQuestionId);
                }
            });
        }else{
            return ResponseEntity.ok(new java.util.HashMap<String, Object>() {
                {
                    put("code", 0);
                    put("msg", "token check failed");
                    put("data", null);
                }
            });
        }

    }
    @PostMapping("/insertQuestionTag")
    public  ResponseEntity<Object> insertQuestionTag(@RequestBody Map<String, Object> requestBody, HttpServletRequest request)
    {
        String token = request.getHeader("Token");
        if (!JwtUtil.checkToken(token)){
            return ResponseEntity.ok(new java.util.HashMap<String, Object>() {
                {
                    put("code", 0);
                    put("msg", "token check  failed");
                    put("data", null);
                }
            });
        }
        Integer questionId = (Integer) requestBody.get("question_id");
        Object tagIdObj = requestBody.get("tag_id");
        List<Integer> tagIds = new ArrayList<>();
        // 处理tag_id可能是单个值或数组的情况
        if (tagIdObj instanceof Integer) {
            tagIds.add((Integer) tagIdObj);
        } else if (tagIdObj instanceof List) {
            tagIds = ((List<?>) tagIdObj).stream()
                    .filter(obj -> obj instanceof Integer)
                    .map(obj -> (Integer) obj)
                    .collect(Collectors.toList());
        }
        if (questionId == null || tagIds.isEmpty()) {
            return ResponseEntity.ok(new HashMap<String, Object>() {{
                put("code", 0);
                put("msg", "invalid parameters");
                put("data", null);
            }});
        }
        int successCount = 0;
        for (Integer tagId : tagIds) {
            QuestionTag questionTag = new QuestionTag();
            questionTag.setQuestion_id(questionId);
            questionTag.setTag_id(tagId);
            successCount += questionService.insertQuestionTag(questionTag);
        }
        int finalSuccessCount = successCount;
        return ResponseEntity.ok(new HashMap<String, Object>() {{
            put("code", finalSuccessCount > 0 ? 1 : 0);
            put("msg", finalSuccessCount > 0 ?
                    "insertQuestionTag success for " + finalSuccessCount + " tags" :
                    "insertQuestionTag failed");
            put("data", null);
        }});
    }

    @GetMapping("/getQuestionTag")
    public ResponseEntity<Object> getQuestionLTag(Tag tag)
    {
        int questionId = tag.getId();
        List<Tag> list = questionService.getQuestionTag(questionId);
        return ResponseEntity.ok(new java.util.HashMap<String, Object>() {
            {
                put("code", (list != null && !list.isEmpty()) ? 1 : 0);
                put("msg", (list != null && !list.isEmpty()) ? "getQuestionTag success" : "getQuestionTag failed");
                put("data", list);
            }
        });
    }
    @GetMapping("/getQuestionComment")
    public ResponseEntity<Object> getQuestionComment(Question question)
    {
        int questionId = question.getId();
        List<Comment> list = questionService.getQuestionComment(questionId);
        return ResponseEntity.ok(new java.util.HashMap<String, Object>() {
            {
                put("code", (list != null && !list.isEmpty()) ? 1 : 0);
                put("msg", (list != null && !list.isEmpty()) ? "getQuestionTag success" : "getQuestionTag failed");
                put("data", list);
            }
        });
    }


    @DeleteMapping("/deleteQuestion")
    public ResponseEntity<Object> deleteQuestion(@RequestBody Question question, HttpServletRequest request) {
        String token = request.getHeader("Token");
        if (!JwtUtil.checkToken(token)){
            return ResponseEntity.ok(new java.util.HashMap<String, Object>() {
                {
                    put("code", 0);
                    put("msg", "token check failed");
                    put("data", null);
                }
            });
        }
        int result3 = questionService.deleteQuestionCommentLike(question);//删除评论点赞
        int result2 = questionService.deleteQuestionLike(question);//删除问题点赞
        int result1 = questionService.deleteQuestion(question);//删除问题（自动删除评论）
        return ResponseEntity.ok(new java.util.HashMap<String, Object>() {
            {
                put("code", result1!= 0&&result2!= 0&&result3!= 0 ? 1 : 0);
                put("msg", result1!= 0&&result2!= 0&&result3!= 0 ? "deleteQuestion success" : "deleteQuestion failed");
                put("data", null);
            }
        });
    }

}
